package com.hmsm.sys.daoImpl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Component;

import com.hmsm.server.base.BaseDao;
import com.hmsm.sys.dao.MenuDao;
import com.hmsm.sys.po.Menu;

@Component
public class MenuDaoImpl extends BaseDao<Menu, Integer> implements MenuDao {
	
	/**
	 *  @描述:根据条件分页获取日志信息
	 *  @方法名称:getInfoList
	 *  @作者:yaosq
	 *  @创建日期:2014-4-1 下午02:09:30 
	 *  @param beginTime
	 *  @param endTime
	 *  @param userName
	 *  @param type
	 *  @param pageIndex
	 *  @param pageSize
	 *  @param pageSize
	 *  @return 分页结果
	 */
	
	@SuppressWarnings("unchecked")
	public List<Menu> getMenuList(final String name, final Menu parent, final Integer pageIndex,
			final Integer pageSize) {
		Object obj = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Criteria cr = session.createCriteria(Menu.class);
				if (name != null) {
					cr.add(Restrictions.ge("name", name));
				}
				if (parent != null) {
					cr.add(Restrictions.le("parent", parent));
				}
				return cr.addOrder(Order.desc("createDate")).setFirstResult((pageIndex - 1) * pageSize).setMaxResults(pageSize).list();
			}
		});
		return (List<Menu>) obj;
	}

	/**
	 *  @描述:根据条件获取日志记录条数
	 *  @方法名称:getMenuCount
	 *  @作者:yaosq
	 *  @创建日期:2014-4-1 下午02:09:30 
	 *  @param beginTime
	 *  @param endTime
	 *  @param userName
	 *  @param type
	 *  @return
	 */
	public int getMenuCount(final String name, final Menu parent) {
		Object obj = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Criteria cr = session.createCriteria(Menu.class);
				if (name != null) {
					cr.add(Restrictions.ge("name", name));
				}
				if (parent != null) {
					cr.add(Restrictions.le("parent", parent));
				}
				return cr.setProjection(Projections.rowCount()).uniqueResult();
			}
		});
		if (obj != null) {
			return Integer.parseInt(obj.toString());
		}
		return 0;
	}

}
